package com.ys.erp.stage_user_service.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.ys.erp.common.util.DateUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.UUID;

/**
 * @author lwj
 * @date 2025/9/12
 */
@Service
@RefreshScope
@RequiredArgsConstructor
public class CosUtil {

    @Value("${cos.bucket}")
    private String bucket;

    private final COSClient cosClient;


    public String upload(InputStream inputStream, String name, String dirName) throws InterruptedException {
        String fileName = Objects.requireNonNull(DateUtil.localDateTimeFormat(LocalDateTime.now())).replaceAll(" ", "-")
                + "-" + UUID.randomUUID()
                + name.substring(name.lastIndexOf("."));
        fileName = fileName.replaceAll("-", "").replaceAll(":", "");
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, dirName+fileName, inputStream, new ObjectMetadata());
        // 高级接口会返回一个异步结果Upload
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        System.out.println(putObjectResult.getDateStr());
        //返回上传对象的key
        return dirName + fileName;
    }

}
